package gwtappcontainer.server.apps.videos;

import static com.googlecode.objectify.ObjectifyService.ofy;
import gwtappcontainer.client.apps.videos.VideoRpcService;
import gwtappcontainer.shared.apis.videos.VideoProp;

import java.util.logging.Logger;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.cmd.Query;


@SuppressWarnings("serial")
public class VideoRpcServiceImpl extends RemoteServiceServlet implements VideoRpcService {
	private Logger logger;
	
	static {
		ObjectifyService.factory().register(VideoEntity.class);	
		ObjectifyService.factory().register(DefaultVideoEntity.class);
	}
	
	public VideoRpcServiceImpl() {
		logger = Logger.getLogger(VideoRpcServiceImpl.class.getName());
	}

	@Override
	public VideoProp getVideoProp(String tag) {
		
		if (tag.equals("")) {
			//get the default video if default exists
			Query<DefaultVideoEntity> all 
				= ofy().load().type(DefaultVideoEntity.class);
			
			if (0 != all.count()) 				
				tag = all.first().get().defaultVideoTag;
			else
				logger.warning("no default video specified");
		}
						
		Query<VideoEntity> all = ofy().load().type(VideoEntity.class);
		
		if (0 != all.count()) {
			//if no match - take the first video
			VideoEntity match = all.first().get();
			boolean found = false;

			for (VideoEntity entity : all) {
				
				if ((entity.tag != null) && entity.tag.equalsIgnoreCase(tag)) {
					match = entity;
					found = true;
										
					logger.info("found matching entity - " + match + 
							" for tag [" + tag + "]");					
				}
			}
				
			if (! found) 
				logger.info("cannot find matching entity for tag " + tag + 
						". returning first entity - " + match.toString());
			
			VideoProp prop = match.getVideoProp();			
			return prop;			
		} else {			
			logger.severe("no video available in datastore.");			
			return null;
		}
	}	
}
